import {reactive, ref, toRaw} from "vue";
import type IPageResp from "@/type/IPageResp.ts";
import resetDefault from "@/util/reset-default.ts";
import type IPageReq from "@/type/IPageReq.ts";
import type ISysSchedulerTaskReq from "./type/req/ISysSchedulerTaskReq.ts";
import type ISysSchedulerTaskResp from "./type/resp/ISysSchedulerTaskResp.ts";
import sysSchedulerTaskApi from "./api/SysSchedulerTaskApi.ts";

/**
 * 基础表结构的CRUD相关代码
 */
export const useSysSchedulerTaskCrud = () => {

    /**
     * 分页数据
     */
    const pageModel = reactive<IPageReq>({
        pageNo: 1,
        pageSize: 10
    })

    /**
     * search表单数据
     */
    const searchModel = reactive<ISysSchedulerTaskReq>({

    })

    /**
     * 表格数据
     */
    const tableModel = reactive<IPageResp<ISysSchedulerTaskResp>>({
        current: 1,
        size: 10,
        pages: 0,
        total: 0,
        records: []
    })

    /**
     * 新增和编辑框数据
     */
    const dialogModel = reactive<ISysSchedulerTaskReq>({
    })

    /**
     * 分页查询
     */
    let loading = ref<boolean>(false)

    const page = () => {
        loading.value = true
        sysSchedulerTaskApi.page({...toRaw(searchModel), ...toRaw(pageModel)})
            .then(result => {
                tableModel.current = result.current
                tableModel.size = result.size
                tableModel.pages = result.pages
                tableModel.total = result.total
                tableModel.records = result.records
            })
            .catch(() => {
                //查询出错，就清空数据
                tableModel.records = []
            })
            .finally(() => {
                loading.value = false
            })
    }

    const reset = () => {
        resetDefault(searchModel)
        page()
    }

    const pageChange = (pageNo: number, pageSize: number) => {
        pageModel.pageNo = pageNo
        pageModel.pageSize = pageSize
        page()
    }

    /**
    * 新增和编辑的dialog
    */
    let dialogVisible = ref(false)
    const openDialog = (row: any) => {
        if (row) {
            Object.assign(dialogModel, row)
        }
        dialogVisible.value = true
    }
                    
    const closeDialog = () => {
        resetDefault(dialogModel)
        dialogVisible.value = false
    }
                    
    const addOrUpdate = async () => {
        await sysSchedulerTaskApi.addOrUpdate(dialogModel)
        closeDialog()
        page()
    }

    /**
    * 删除
    */
    const deleteByIds = async (ids: string[]) => {
        await sysSchedulerTaskApi.deleteById(ids)
        page()
    }

    return {
        searchModel,
        tableModel,
        dialogModel,
        loading,
        dialogVisible,
        page,
        reset,
        pageChange,
        openDialog,
        closeDialog,
        addOrUpdate,
        deleteByIds
    }
}